import logging
import nmap
import pymysql
import pymysql.cursors
from contextlib import contextmanager
from pythonping import ping


def can_connect(ip_address):
    try:
        response_list = ping(ip_address, count=1, timeout=60)
        if response_list.stats_packets_returned:
            return True
        return False
    except Exception as e:
        print(f"Error: {e}")
        return False

def scan_open_ports(ip_address):
    nm = nmap.PortScanner()
    nm.scan(ip_address, arguments='-p1-65535')
    res = {}
    for host in nm.all_hosts():
        port_service = nm[host]['tcp']
        res[host] = port_service
    return res

class DBSql:

    def __init__(self):
        self.host = '127.0.0.1'
        self.user = 'root'
        self.password = 'PwcZ7QtIZ4m1E8V0'
        self.db = 'artical_scan'
        self.port = 3306
        self.conn = None
        self.cursor = None

    def create_conn(self):
        '''创建链接'''
        self.conn = pymysql.connect(host=self.host, user=self.user,
                                        password=self.password, db=self.db, 
                                        port=self.port, cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()


    @contextmanager
    def query_all(self, sql_text, params=None):
        '''查询所有'''

        self.create_conn()
        self.cursor.execute(sql_text, params) if params else self.cursor.execute(sql_text)
        resp = self.cursor.fetchall()
        # data = [dict(row) for row in resp]
        yield resp
        self.conn.close()

    @contextmanager
    def query(self, sql_text, params=None):
        '''查询单个'''
        self.create_conn()
        self.cursor.execute(sql_text, params) if params else self.cursor.execute(sql_text)
        resp = self.cursor.fetchall()
        data = dict(resp[0])
        yield data
        self.conn.close()


    @contextmanager
    def insert(self,sql_text, params=None):
        '''插入/更新'''
        self.create_conn()
        self.cursor.execute(sql_text, params) if params else self.cursor.execute(sql_text)
        last_insert_id = self.cursor.lastrowid
        yield last_insert_id
        self.conn.commit()
        self.conn.close()
        
    @contextmanager
    def insert_many(self,sql_text,params=None):
        self.create_conn()
        try:
            self.cursor.executemany(sql_text,params)
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        yield
        self.conn.close()


    @contextmanager
    def query_pd(self):
        self.create_conn()
        yield
        self.conn.close()



    def delete(self):
        '''删除'''
        pass


    def __del__(self):
        '''销毁链接'''
        try:
            self.conn.close()
        except:
            pass


if __name__ == "__main__":
    # ip_address = 'www.baidu.com'
    ip_address = '192.168.10.41'
    # can_connect(ip_address)
    res = scan_open_ports(ip_address)
    print(res)